package com.adb.dao;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;

import com.adb.entity.GameDraft;

public class GameDraftManager {
	private ArrayList<GameDraft> gameDraftList = new ArrayList<GameDraft>();

	private GameDraft gameDraft;

	public void setGameDraft(Cursor cursor) {
		gameDraft = new GameDraft();
		gameDraft.id = cursor.getInt(cursor.getColumnIndex("id"));
		gameDraft.avID = cursor.getInt(cursor.getColumnIndex("avID"));
		gameDraft.num = cursor.getInt(cursor.getColumnIndex("num"));
		gameDraft.draft = cursor.getString(cursor.getColumnIndex("draft"));
	}

	public ArrayList<GameDraft> getGameDraftListByAVId(Context context, int avID) {
		GameDraftDao gameDraftDao = new GameDraftDao(context);
		String sql = "select * from " + GameDraftDao.tableName + " where avID="
				+ avID;
		Cursor cursor = gameDraftDao.Query(sql);
		for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
			setGameDraft(cursor);
			gameDraftList.add(gameDraft);
		}
		cursor.close();
		gameDraftDao.close();
		return gameDraftList;
	}

	private void insert(Context context, GameDraft gameDraft) {
		GameDraftDao gameDraftDao = new GameDraftDao(context);
		gameDraftDao.insert(gameDraft);
		gameDraftDao.close();
	}

	private void update(Context context, GameDraft gameDraft) {
		GameDraftDao gameDraftDao = new GameDraftDao(context);
		gameDraftDao.update(gameDraft);
		gameDraftDao.close();
	}

	public void save(Context context, GameDraft gameDraft) {
		GameDraft temp = getGameDraftByAvIDAndNum(context, gameDraft.avID,
				gameDraft.num);
		if (null != temp && temp.id > 0) {
			temp.draft = gameDraft.draft;
			update(context, temp);
		} else {
			insert(context, gameDraft);
		}
	}

	private GameDraft getGameDraftByAvIDAndNum(Context context, int avID,
			int num) {
		GameDraftDao gameDraftDao = new GameDraftDao(context);
		Cursor cursor = gameDraftDao.Query("select * from "
				+ GameDraftDao.tableName + " where avID=" + avID + " and num="
				+ num);
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			setGameDraft(cursor);
		}
		cursor.close();
		gameDraftDao.close();
		return gameDraft;
	}
}
